const onDocumentReady = () => new Promise(resolve => {
    if (document.addEventListener) {
        document.addEventListener('DOMContentLoaded', function () {
            document.removeEventListener('DOMContentLoaded', arguments.callee, false);
            resolve();
        }, false);
    }
});

const sleep = (ms) => new Promise(resolve => setTimeout(resolve, ms));

async function init() {
    await onDocumentReady();
    document.addEventListener('keydown', (e) => {
        if (e.key === 'F2') {
            // 获取要聚焦的文本框元素
            const textBox = document.getElementById('message-input');
            if (textBox) {
                textBox.focus();
            }
        }
    });
    const textarea = document.querySelector('textarea');
    if (textarea) {
        textarea.addEventListener('input', (e) => {
            textarea.style.height = '40px';
            textarea.style.height = e.target.scrollHeight + 'px';
        });
        textarea.addEventListener('keydown', (e) => {
            if (e.key === 'Enter' && !e.shiftKey) {
                // 获取要提交的form表单
                const form = document.getElementById('message-form');
                if (form) {
                    // 防止多次提交
                    form.addEventListener('submit', (e) => e.preventDefault(), { once: true });
                    form.submit();
                }
                // 不产生换行
                e.preventDefault();
            }
        });
    }
    if (phase != 'idle' && current_thread) {
        let oldLen = null;
        let oldMsg = null;
        let oldCall = null;
        if (phase == 'responsing') {
            fetch('/start_response', {
                method: 'POST',
                headers: {
                    "Content-Type": "application/json",
                },
                body: JSON.stringify({
                    thread: current_thread,
                }),
            });
            // window.location.replace(window.location.href);
        }
        while (true) {
            const res = await fetch('/get_response', {
                method: 'POST',
                headers: {
                    "Content-Type": "application/json",
                },
                body: JSON.stringify({
                    thread: current_thread,
                }),
            });
            const data = await res.json();
            const nowLen = data.messages.length;
            if (oldLen === null) {
                // console.log('new');
                oldLen = nowLen;
            } else if (nowLen !== oldLen || data.responsing === false) {
                // console.log('refr');
                window.location.replace(window.location.href);
                break;
            } else {
                // console.log('upd');
                const msg = data.messages.length <= 0 ? null : data.messages[data.messages.length - 1].content;
                const call = data.messages.length <= 0 ? null : data.messages[data.messages.length - 1].tool_calls;
                if (msg !== oldMsg) {
                    // console.log('mism');
                    const lastContent = document.getElementById('last-content');
                    if (lastContent) {
                        const lines = msg.split('\n');
                        lastContent.innerHTML = '';
                        // add <p> for each line:
                        lines.forEach(line => {
                            const p = document.createElement('p');
                            p.innerText = line;
                            lastContent.appendChild(p);
                        });
                        const div = document.getElementById('chat-box');
                        div.scrollTop = div.scrollHeight;
                    // } else {
                        // console.log('nolc!!!');
                    }
                }
                const callStr = JSON.stringify(call);
                if (call && callStr !== oldCall) {
                    const lastCall = document.getElementById('last-tool-call');
                    if (lastCall) {
                        lastCall.innerHTML = '';
                        call.forEach(tool_call => {
                            if (tool_call.type == 'function') {
                                /* <div class="tool-call">
                                    <span class="tool-name">{{ tool_call.function.name }}</span>
                                    <span class="tool-arguments" title="{{ tool_call.function.arguments }}">({{ tool_call.function.arguments }})</span>
                                </div> */
                                const div = document.createElement('div');
                                div.classList.add('tool-call');
                                const spanName = document.createElement('span');
                                spanName.classList.add('tool-name');
                                spanName.innerText = tool_call.function.name;
                                div.append(spanName);
                                const spanArguments = document.createElement('span');
                                spanArguments.classList.add('tool-arguments');
                                spanArguments.setAttribute('title', tool_call.function.arguments);
                                spanArguments.innerText = `(${tool_call.function.arguments})`;
                                div.append(spanArguments);
                                lastCall.append(div);
                            }
                        });
                    }
                }
                oldMsg = msg;
                oldCall = callStr;
            }
            oldLen = nowLen;
            await sleep(200);
        }
    } else if (!choices_ready && current_thread) {
        for (let retry = 0; retry < 20; retry++) {
            await sleep(300);
            const res = await fetch('/get_choices', {
                method: 'POST',
                headers: {
                    "Content-Type": "application/json",
                },
                body: JSON.stringify({
                    thread: current_thread,
                }),
            });
            const data = await res.json();
            if (data.choices_ready) {
                const div = document.getElementById('chat-box');
                const wasBottom = div.scrollTop + div.offsetHeight >= div.scrollHeight - 1;
                let html = '<div class="row" id="choices-list">';
                data.choices.forEach(choice => {
                    html += '<form class="inline" action="/send_message" method="post">'
                        + '<input type="text" name="query" class="hidden" value="' + choice + '" autocomplete="off">'
                        + '<input type="text" name="thread" class="hidden" value="' + current_thread + '" autocomplete="off">'
                        + '<input type="submit" class="choice-button" title="' + choice + '" value="' + choice + '">'
                        + '</form>';
                });
                html += '</div>';
                div.innerHTML += html;
                if (wasBottom) {
                    div.scrollTop = div.scrollHeight;
                }
                break;
            }
        }
    }
}

init();
